package com.security.activity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.security.Adapter.AdpBean;
import com.security.Adapter.MyAdapter;
import com.security.R;
import com.security.broadcast.MyAdmin;
import com.security.location.GPSUtil;
import com.security.service.SecurityService;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class HomeActivity extends AppCompatActivity {
    private List<AdpBean> list;
    private Switch switch1;
    private DevicePolicyManager dpm;
    SharedPreferences sp;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        sp=getSharedPreferences("data",Context.MODE_PRIVATE);

        switch1=findViewById(R.id.switch1);

        dpm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);

        list=new ArrayList<>();
        initData(); 
        MyAdapter adapter=new MyAdapter(HomeActivity.this,R.layout.item,list);

        ListView listView=findViewById(R.id.lv);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener((parent, view, position, id) -> {
            switch (position){
                case 0:
                    EditText ed=new EditText(getApplicationContext());
                    ed.setHint("建议使用亲属手机号");
                    AlertDialog.Builder dialog=new AlertDialog.Builder(HomeActivity.this);
                    dialog.setTitle("绑定安全手机号");
                    dialog.setView(ed);
                    dialog.setPositiveButton("确定", (dialogInterface, i) -> {
                        if (isPhoneLegal(ed.getText().toString())){
                            SharedPreferences.Editor editor = sp.edit();
                            editor.putString( "securityMobile", ed.getText().toString());
                            editor.apply();
                            list.get(position).setName("绑定安全手机:"+sp.getString("securityMobile","未绑定"));
                            adapter.notifyDataSetChanged();
                        }else{
                            Toast.makeText(getApplicationContext(),"不是大陆或香港手机号！",Toast.LENGTH_SHORT).show();
                        }
                    });
                    dialog.setNegativeButton("取消",null);
                    dialog.show();
                    break;
                case 1:
                    if (sp.getBoolean("detectSIM",false)){
                        list.get(position).setName("SIM卡被更换检测:未开启");
                        adapter.notifyDataSetChanged();
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putBoolean( "detectSIM", false);
                        editor.apply();
                    }else {
                        list.get(position).setName("SIM卡被更换检测:已开启");
                        adapter.notifyDataSetChanged();
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putBoolean( "detectSIM", true);
                        editor.apply();
                    }
                    break;
                case 2:
                    if (sp.getBoolean("detectLocation",false)){
                        list.get(position).setName("手机定位:未开启");
                        adapter.notifyDataSetChanged();
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putBoolean( "detectLocation", false);
                        editor.apply();
                    }else {
                        list.get(position).setName("手机定位:已开启");
                        adapter.notifyDataSetChanged();
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putBoolean( "detectLocation", true);
                        editor.apply();
                    }
                    break;
                case 3:
                    if (sp.getBoolean("destroyData",false)){
                        list.get(position).setName("通过短信销毁数据:未开启");
                        adapter.notifyDataSetChanged();
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putBoolean( "destroyData", false);
                        editor.apply();
                    }else {
                        list.get(position).setName("通过短信销毁数据:已开启");
                        adapter.notifyDataSetChanged();
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putBoolean( "destroyData", true);
                        editor.apply();
                    }
                    break;
                case 4:
                    if (sp.getBoolean("lockMobile",false)){
                        list.get(position).setName("通过短信锁定手机:未开启");
                        adapter.notifyDataSetChanged();
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putBoolean( "lockMobile", false);
                        editor.apply();
                    }else {
                        list.get(position).setName("通过短信锁定手机:已开启");
                        adapter.notifyDataSetChanged();
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putBoolean( "lockMobile", true);
                        editor.apply();
                    }
                    ComponentName who = new ComponentName(HomeActivity.this, MyAdmin.class);
                    if (!dpm.isAdminActive(who)) {
                        Toast.makeText(HomeActivity.this, "请先开启管理员权限!", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
                        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, who);
                        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "开启可以一键锁屏，防止勿碰");
                        startActivity(intent);
                    }
                    break;
                case 5:
                    if (sp.getBoolean("alarm",false)){
                        list.get(position).setName("通过短信播放警铃:未开启");
                        adapter.notifyDataSetChanged();
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putBoolean( "alarm", false);
                        editor.apply();
                    }else{
                        list.get(position).setName("通过短信播放警铃:已开启");
                        adapter.notifyDataSetChanged();
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putBoolean( "alarm", true);
                        editor.apply();
                    }
                    break;
                case 6:
                    startActivity(new Intent(HomeActivity.this,MainActivity.class));
                    finish();
                    break;
                case 7:
                    finish();
                    break;
            }
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {ActivityCompat.requestPermissions(this,new String[]{
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_SMS,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.SEND_SMS,
                Manifest.permission.WAKE_LOCK},1); }
        GPSUtil gpsUtil=new GPSUtil(this);
        gpsUtil.apply();

        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock mwl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyTag");
        mwl.acquire();//屏幕关闭后保持活动

    }
    public static boolean isServiceRunning(Context context, String ServiceName) {
        if (TextUtils.isEmpty(ServiceName)) {
            return false;
        }
        ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager.getRunningServices(1000);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().equals(ServiceName)) {
                return true;
            }
        }
        return false;
    }
    private void initData(){
        String str=(sp.getBoolean("detectSIM",false))?"已开启":"未开启";
        AdpBean a=new AdpBean("绑定安全手机:"+sp.getString("securityMobile","未绑定"),R.drawable.mobile);
        list.add(a);
        AdpBean b=new AdpBean("SIM卡被更换检测:"+str,R.drawable.sim);
        list.add(b);
        str=(sp.getBoolean("detectLocation",false))?"已开启":"未开启";
        AdpBean c=new AdpBean("手机定位:"+str,R.drawable.location);
        list.add(c);
        str=(sp.getBoolean("destroyData",false))?"已开启":"未开启";
        AdpBean d=new AdpBean("通过短信销毁数据:"+str,R.drawable.data);
        list.add(d);
        str=(sp.getBoolean("lockMobile",false))?"已开启":"未开启";
        AdpBean e=new AdpBean("通过短信锁定手机:"+str,R.drawable.lock);
        list.add(e);
        str=(sp.getBoolean("alarm",false))?"已开启":"未开启";
        AdpBean f=new AdpBean("通过短信播放警铃:"+str,R.drawable.ring);
        list.add(f);
        AdpBean g=new AdpBean("退出登录",R.drawable.exit);
        list.add(g);
        AdpBean h=new AdpBean("关闭(若服务开启则自动后台低耗)",R.drawable.exit);
        list.add(h);
    }
    public void usage(View view) {
        AlertDialog.Builder dialog=new AlertDialog.Builder(HomeActivity.this);
        dialog.setTitle("使用方法");
        dialog.setMessage(R.string.usage);
        dialog.setPositiveButton("确定", null);
        dialog.show();
    }
    public void switchService(View view) {
        if (!isServiceRunning(HomeActivity.this, "com.security.activity.HomeActivity")){
            switch1.setChecked(true);
            startService(new Intent(HomeActivity.this, SecurityService.class));
        }else {
            switch1.setChecked(false);
            stopService(new Intent(HomeActivity.this,SecurityService.class));
        }
    }
    public static boolean isPhoneLegal(String str) throws PatternSyntaxException {
        return isChinaPhoneLegal(str) || isHKPhoneLegal(str);
    }
    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])"+"|(18[0-9])|(19[8,9]))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }
    public static boolean isHKPhoneLegal(String str) throws PatternSyntaxException {
        String regExp = "^([5689])\\d{7}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }
}